<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .progress-bar {
            background-color: greenyellow;
            height: 20px;
        }
    </style>
</head>
<div class="progress-bar"></div>

<body>
    <script>
        function loadingBar(ele) {
            // 使用闭包保存定时器的编号
            let handle;
            return () => {
                // 每次触发将进度清空
                ele.style.width = "0";
                // 开始动画前清除上一次的动画定时器
                // 否则会开启多个定时器
                cancelAnimationFrame(handle);
                // 回调函数
                let _progress = () => {
                    let eleWidth = parseInt(ele.style.width);

                    if (eleWidth < 600) {
                        ele.style.width = `${eleWidth + 1}px`;
                        handle = requestAnimationFrame(_progress);
                    } else {
                        cancelAnimationFrame(handle);
                    }
                };
                handle = requestAnimationFrame(_progress);

            };
        }

        function loadingBar2(ele) {
            let handle;
            return () => {
                // 每次触发将进度清空
                ele.style.width = "0";
                // 开始动画前清除上一次的动画定时器
                // 否则会开启多个定时器
                clearInterval(handle);
                // 回调函数
                handle = setInterval(() => {
                    let eleWidth = parseInt(ele.style.width);
                    if (eleWidth < 600) {
                        ele.style.width = `${eleWidth + 1}px`;
                    } else {
                        clearInterval(handle);
                    }
                }, 2000)
            };
        }
        let pb = document.querySelector('.progress-bar');
        loadingBar2(pb)()
    </script>
</body>

</html>